<template>
    <!-- 员工数据展示表格 -->
    <el-table :data="GetCostData" style="width: 100%" highlight-current-row>
        <el-table-column fixed prop="CostYear" label="年份" align="center"/>
        <el-table-column prop="CostMonth" label="月度" align="center"/>
        <el-table-column prop="CostPrice" label="成本" align="center" >
            <template #default="{ row }">
                ¥{{ row.CostPrice.toFixed(2) }}
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="180" align="center">
            <template #default="ThisRowData">
                <el-button size="small" type="primary" @click="EditEmployeeClick(ThisRowData.row)">修改</el-button>
            </template>
        </el-table-column>

        <template #empty>
            <el-empty description="暂无员工数据" />
        </template>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="员工数据管理">
        <el-form :model="formData" ref="formRef" label-width="80px">
            <el-form-item label="年份" prop="CostYear">
                <el-input v-model.number="formData.CostYear" placeholder="请输入年份"></el-input>
            </el-form-item>
            <el-form-item label="月度" prop="CostMonth">
                <el-input v-model.number="formData.CostMonth" placeholder="请输入月度"></el-input>
            </el-form-item>
            <el-form-item label="成本" prop="CostPrice">
                <el-input v-model.number="formData.CostPrice" placeholder="请输入成本"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveEmployee">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang='ts' setup name=''>
import axios from 'axios';
import { reactive, ref, onMounted, watch, nextTick } from 'vue';
import { ElNotification, ElMessageBox, ElForm } from 'element-plus';
import { Search } from '@element-plus/icons-vue';

// 表格数据
let GetCostData = ref([
    {
        CostYear: 2025,
        CostMonth: 5,
        CostPrice: 12
    }
]);

// 搜索表单
const searchForm = reactive({
    year: '',
    month: ''
});

// 对话框相关
const dialogVisible = ref(false);
const formData = reactive({
    CostYear: 0,
    CostMonth: 0,
    CostPrice: 0
});
const formRef = ref<InstanceType<typeof ElForm>>();
let isEdit = ref(false); // 判断是新增还是编辑
let currentId = ref(null); // 当前操作的数据ID

// 表单验证规则
const rules = reactive({
    CostYear: [
        { required: true, message: '请输入年份', trigger: 'blur' },
        { type: 'number', message: '年份必须为数字值', trigger: 'blur' }
    ],
    CostMonth: [
        { required: true, message: '请输入月度', trigger: 'blur' },
        { type: 'number', message: '月度必须为数字值', trigger: 'blur' }
    ],
    CostPrice: [
        { required: true, message: '请输入成本', trigger: 'blur' },
        { type: 'number', message: '成本必须为数字值', trigger: 'blur' }
    ]
});

// GET ------------------------------------------ GET //
// 获取员工数据
const fetchData = async () => {
    try {
        // 实际项目中这里应该调用后端API
        // const response = await axios.get('/api/employees', { params: searchForm });
        // GetCostData.value = response.data;
        
        // 模拟数据加载延迟
        setTimeout(() => {
            // 这里使用模拟数据，实际项目中应替换为真实API调用
            if (searchForm.year || searchForm.month) {
                // 模拟搜索过滤
                GetCostData.value = GetCostData.value.filter(item => {
                    const yearMatch = !searchForm.year || item.CostYear === parseInt(searchForm.year);
                    const monthMatch = !searchForm.month || item.CostMonth === parseInt(searchForm.month);
                    return yearMatch && monthMatch;
                });
            }
            ElNotification({
                title: '成功',
                message: '数据加载成功',
                type: 'success'
            });
        }, 500);
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '数据加载失败',
            type: 'error'
        });
        console.error('获取员工数据失败:', error);
    }
};

// 搜索数据
const searchData = () => {
    fetchData();
};

// 重置搜索
const resetSearch = () => {
    searchForm.year = '';
    searchForm.month = '';
    fetchData();
};

// POST ------------------------------------------ POST //
// 新增员工
const addEmployee = async () => {
    try {
        // 实际项目中这里应该调用后端API
        // const response = await axios.post('/api/employees', formData);
        
        // 模拟添加数据
        const newItem = { ...formData };
        GetCostData.value.push(newItem);
        
        ElNotification({
            title: '成功',
            message: '添加员工成功',
            type: 'success'
        });
        dialogVisible.value = false;
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '添加员工失败',
            type: 'error'
        });
        console.error('添加员工失败:', error);
    }
};

// PUT ------------------------------------------ PUT //
// 修改员工
const updateEmployee = async () => {
    try {
        // 实际项目中这里应该调用后端API
        // const response = await axios.put(`/api/employees/${currentId.value}`, formData);
        
        // 模拟更新数据
        const index = GetCostData.value.findIndex(item => 
            item.CostYear === formData.CostYear && 
            item.CostMonth === formData.CostMonth
        );
        if (index !== -1) {
            GetCostData.value[index] = { ...formData };
        }
        
        ElNotification({
            title: '成功',
            message: '更新员工成功',
            type: 'success'
        });
        dialogVisible.value = false;
    } catch (error) {
        ElNotification({
            title: '错误',
            message: '更新员工失败',
            type: 'error'
        });
        console.error('更新员工失败:', error);
    }
};

// 保存员工数据（新增或编辑）
const saveEmployee = () => {
    formRef.value?.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                updateEmployee();
            } else {
                addEmployee();
            }
        } else {
            ElNotification({
                title: '警告',
                message: '请填写完整信息',
                type: 'warning'
            });
            return false;
        }
    });
};

// DELETE ------------------------------------------ DELETE //
// 删除员工
const deleteEmployee = (row) => {
    ElMessageBox.confirm(
        '确定要删除该员工数据吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            // 实际项目中这里应该调用后端API
            // await axios.delete(`/api/employees/${row.id}`);
            
            // 模拟删除数据
            GetCostData.value = GetCostData.value.filter(item => 
                item.CostYear !== row.CostYear || 
                item.CostMonth !== row.CostMonth
            );
            
            ElNotification({
                title: '成功',
                message: '删除员工成功',
                type: 'success'
            });
        } catch (error) {
            ElNotification({
                title: '错误',
                message: '删除员工失败',
                type: 'error'
            });
            console.error('删除员工失败:', error);
        }
    }).catch(() => {
        // 取消操作，无需处理
    });
};

// 打开新增对话框
const openAddDialog = () => {
    isEdit.value = false;
    // 重置表单数据
    formData.CostYear = 0;
    formData.CostMonth = 0;
    formData.CostPrice = 0;
    dialogVisible.value = true;
    
    // 重置表单验证状态
    nextTick(() => {
        formRef.value?.resetFields();
    });
};

// 编辑员工点击事件
const EditEmployeeClick = (row) => {
    isEdit.value = true;
    // 复制数据到表单
    formData.CostYear = row.CostYear;
    formData.CostMonth = row.CostMonth;
    formData.CostPrice = row.CostPrice;
    dialogVisible.value = true;
    
    // 重置表单验证状态
    nextTick(() => {
        formRef.value?.resetFields();
    });
};

// 生命周期钩子
onMounted(() => {
    fetchData();
});
</script>

<style scoped>
.search-card {
    margin-bottom: 16px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>    